<template>
  <div class="page-container">
    <div class="top" v-global-loading="loadingTop">
      <div
        class="page-card-container-item"
        v-for="(item, index) in essentialData"
      >
        <div
          class="border"
          style="
            height: 46px;
            font-size: 12px;
            color: rgb(116, 110, 110);
            line-height: 26px;
          "
        >
          {{ item.title }}
        </div>
        <div
          class="border"
          style="height: 80px; font-size: 26px; color: #000; line-height: 60px"
        >
          <span v-if="index != 2">{{
            formatMoney(String(item.num), false, false)
          }}</span>
          <span v-else>{{ formatMoney(String(item.num), true) }}</span>
        </div>
        <div
          style="
            height: 46px;
            display: flex;
            justify-content: space-between;
            line-height: 60px;
            color: rgb(116, 110, 110);
          "
        >
          <div>{{ item.name }}</div>
          <div>{{ item.quantity }}{{ item.specification }}</div>
        </div>
      </div>
    </div>
    <div class="page-card-container-box">
      <div class="nav">
        <div @click="goNewPage('/merchandise/commodity')">
          <img src="@/assets/imgs/shangping.png" />
          <p>商品管理</p>
        </div>
        <div @click="goNewPage('/customerArchives/memberManagement')">
          <img src="@/assets/imgs/kehu.png" />
          <p>客户管理</p>
        </div>
        <div @click="goNewPage('/orderManagement/orderManagementList')">
          <img src="@/assets/imgs/dingdan.png" />
          <p>订单管理</p>
        </div>
        <div @click="goNewPage('/discount/discountList')">
          <img src="@/assets/imgs/quan.png" />
          <p>电子券管理</p>
        </div>
        <div @click="goNewPage('/orderManagement/behalfConsumer')">
          <img src="@/assets/imgs/daike.png" />
          <p>代客下单</p>
        </div>
        <div @click="goNewPage('/finance/journalAccount')">
          <img src="@/assets/imgs/caiwu.png" />
          <p>财务管理</p>
        </div>
        <div @click="goNewPage('/orderManagement/exportingInformation')">
          <img src="@/assets/imgs/rizhi.png" />
          <p>日志管理</p>
        </div>
      </div>
      <a-divider style="height: 2px; background-color: #e7ecf5" />
      <div style="margin-bottom: 20px">
        <img
          src="@/assets/imgs/tongji.png"
          alt=""
          style="width: 20px; margin-right: 10px"
        />
        <span>统计</span>
      </div>
      <div class="tongji">
        <div v-global-loading="loadingCommodity">
          <span style="font-size: 16px; font-weight: 900; color: #464646"
            >商品分析</span
          >
          <div ref="commodityRef" class="commodityRef tongjiDev"></div>
        </div>
        <div v-global-loading="loadingTransaction">
          <span style="font-size: 16px; font-weight: 900; color: #464646"
            >本月成交额</span
          >
          <a-date-picker
            @change="getNewData($event, 'transaction')"
            style="width: 100px; padding: 2px 8px; margin-left: 10px"
            :allowClear="false"
            v-model:value="transactionDate"
            picker="month"
            value-format="YYYY-MM"
            format="YYYY-MM"
          />
          <div
            id="transactionRef"
            class="tongjiDev"
            style="margin-top: 10px"
          ></div>
        </div>
        <div v-global-loading="loadingOrderForm">
          <span style="font-size: 16px; font-weight: 900; color: #464646"
            >本月订单数</span
          >
          <a-date-picker
            @change="getNewData($event, 'orderForm')"
            style="width: 100px; padding: 2px 8px; margin-left: 10px"
            :allowClear="false"
            v-model:value="orderFormDate"
            picker="month"
            value-format="YYYY-MM"
            format="YYYY-MM"
          />
          <div
            id="orderFormRef"
            class="tongjiDev"
            style="margin-top: 10px"
          ></div>
        </div>
      </div>
      <a-divider style="height: 2px; background-color: #e7ecf5" />
      <div v-global-loading="loadingYearTransaction">
        <div
          id="yearTransactionRef"
          class="tongjiDev"
          ref="yearTransactionRef"
          style="margin-bottom: 30px"
        ></div>
      </div>
      <div v-global-loading="loadingTransactionTop">
        <p
          style="
            font-size: 16px;
            font-weight: 900;
            margin-bottom: 10px;
            color: #464646;
            text-align: center;
          "
        >
          本⽉客户成交额TOP10
        </p>
        <div id="transactionTopRef" style="margin: auto"></div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import {ref, onMounted} from "vue";
import {formatMoney} from "@/utils/common";
import * as echarts from "echarts";
import {Column} from "@antv/g2plot";
import {useRouter} from "vue-router";
import {message} from "ant-design-vue";
import dayjs from "dayjs";
import {
  homeGetMemberCount,
  homeGetOrderCount,
  homeGetGetMakeBargain,
  homeGetMakeBargain,
  homeGetMonethOrder,
  homeGetYearCount,
  homeGetMonethTopTenDto,
  homeGetProductTopDto
} from "@/api/home/home";
import useUserStore from "@/store/user";
//路由跳转
import routerDetails from "@/router";
//成交额日期
const transactionDate = ref(dayjs().format("YYYY-MM"));
//订单数日期
const orderFormDate = ref(dayjs().format("YYYY-MM"));
const router = useRouter();
const routerList = routerDetails.getRoutes();

const goNewPage = (data) => {
  console.log(routerList);

  let toPathHave = routerList.some((route) => {
    return route.path == data;
  });
  if (toPathHave) {
    router.push({path: data});
  } else {
    message.error("抱歉暂无该页面权限,请联系管理员!");
  }
};
const loadingTop = ref(false);
const loadingCommodity = ref(false);
const loadingTransaction = ref(false);
const loadingOrderForm = ref(false);
const loadingYearTransaction = ref(false);
const loadingTransactionTop = ref(false);
const commodityRef = ref();
const yearTransactionRef = ref();
//获取头部信息
const getessentialData = async () => {
  loadingTop.value = true;
  try {
    //会员
    let data = await homeGetMemberCount();
    essentialData.value[0].num = data.data.membersCount;
    essentialData.value[0].quantity = data.data.membersCount;
    essentialData.value[3].num = data.data.newMonethMembers;
    essentialData.value[3].quantity = data.data.newMonethMembers;
  } catch {
    essentialData.value[0].num = "0";
    essentialData.value[0].quantity = "0";
    essentialData.value[3].num = "0";
    essentialData.value[3].quantity = "0";
  }

  try {
    //订单、总金额
    let data = await homeGetOrderCount();
    essentialData.value[1].num = data.data.ordersCount;
    essentialData.value[1].quantity = data.data.orderYesterDay;
    essentialData.value[2].num = data.data.ordersMoney;
    essentialData.value[2].quantity = data.data.hebdomadCount;
  } catch {
    essentialData.value[1].num = "0";
    essentialData.value[1].quantity = "0";
    essentialData.value[2].num = "0";
    essentialData.value[2].quantity = "0";
  }

  try {
    //客户、成交
    let data = await homeGetGetMakeBargain();
    essentialData.value[4].num = data.data.monethClient;
    essentialData.value[4].quantity = data.data.monethOrder;
  } catch {
    essentialData.value[4].num = "0";
    essentialData.value[4].quantity = "0";
  }
  loadingTop.value = false;
};
const essentialData = ref<Array<any>>([
  {
    title: "会员总数",
    num: "",
    name: "会员总数",
    quantity: "",
    specification: ""
  },
  {
    title: "订单总数",
    num: "",
    name: "昨日订单数",
    quantity: "",
    specification: "单"
  },
  {
    title: "总金额",
    num: "",
    name: "近七天订单数",
    quantity: "",
    specification: "单"
  },
  {
    title: "本月新增会员数",
    num: "",
    name: "本月新增会员数",
    quantity: "",
    specification: ""
  },
  {
    title: "当月成交客户数",
    num: "",
    name: "当月成交订单数量",
    quantity: "",
    specification: ""
  }
]);
//获取月份中有多少天
function GetDays(date) {
  let year = Number(dayjs(date).format("YYYY"));
  let month = Number(dayjs(date).format("MM"));
  let data = new Date(year, month, 0);
  return data.getDate();
}
//绘制图表
onMounted(() => {
  //绘制头部
  getessentialData();
  //绘制商品信息
  getCommodity();
  //本月成交额
  getTransaction();
  //本月订单数
  getOrderForm();
  //本年成交额
  getYearTransaction();
  //销售前十
  getTransactionTop();
});
//商品信息
let commodityData = ref<Array<any>>([]); //商品分析数据
const getCommodity = async () => {
  loadingCommodity.value = true;
  commodityData.value = [];
  try {
    let data = await homeGetProductTopDto();
    let num = 0; //已有商品数量
    let num1; //商品总数
    if (data.data.length) {
      data.data.forEach((item) => {
        num1 = Number(item.salesCount);
        num += Number(item.salesVolume);
        commodityData.value.push({
          value: item.salesVolume,
          name: item.productName + item.spec
        });
      });
      commodityData.value.push({value: num1 - num, name: "其他"});
    }
  } catch {
    commodityData.value.push({value: 0, name: "其他"});
  }
  commodity();
  loadingCommodity.value = false;
};
//绘制商品分析图
const commodity = () => {
  if (!commodityRef.value) {
    return false;
  }
  var myChart = echarts.init(commodityRef.value);
  var option;
  option = {
    color: ["#5ab1ef ", "#3dc6c9", "#b6a2dd", "#fac858", "#5c7bd9"],
    tooltip: {
      trigger: "item",
      position: "right"
    },
    // legend: {
    //   orient: "horizontal",
    //   bottom: 0
    // },
    series: [
      {
        name: "商品分析",
        type: "pie",
        radius: "50%",
        data: commodityData.value
      }
    ]
  };
  option && myChart.setOption(option);
};
//本月成交额
const TransactionData = ref<Array<any>>([]);
const getTransaction = async () => {
  loadingTransaction.value = true;
  TransactionData.value = [];
  let dateNum = GetDays(transactionDate.value); //当月有多少天
  for (let index = 1; index <= dateNum; index++) {
    TransactionData.value.push({
      type: index + "日",
      sales: 0
    });
  }
  try {
    let data = await homeGetMakeBargain({dateTime: transactionDate.value});
    data.data.forEach((item, index) => {
      let num = Number(dayjs(item.key).format("DD"));
      TransactionData.value[num - 1].sales = item.value;
    });
  } catch {}
  transaction();
  loadingTransaction.value = false;
};
const columnPlot1 = ref();
const transaction = () => {
  if (!document.querySelector("#transactionRef")) {
    return false;
  }
  if (columnPlot1.value) {
    columnPlot1.value.changeData(TransactionData.value);
  } else {
    columnPlot1.value = new Column("transactionRef", {
      data: TransactionData.value,
      xField: "type",
      yField: "sales",
      meta: {
        type: {
          alias: "天"
        },
        sales: {
          alias: "成交额"
        }
      }
    });
    columnPlot1.value.render();
  }
};
//本月订单数
const getOrderData = ref<Array<any>>([]);
const getOrderForm = async () => {
  loadingOrderForm.value = true;
  let dateNum = GetDays(orderFormDate.value); //当月有多少天
  for (let index = 1; index <= dateNum; index++) {
    getOrderData.value.push({
      type: index + "日",
      sales: 0
    });
  }
  try {
    let data = await homeGetMonethOrder({dateTime: orderFormDate.value});
    data.data.forEach((item, index) => {
      let num = Number(dayjs(item.key).format("DD"));
      getOrderData.value[num - 1].sales = item.value;
    });
  } catch {}
  orderForm();
  loadingOrderForm.value = false;
};
const columnPlot2 = ref();
const orderForm = () => {
  if (!document.querySelector("#orderFormRef")) {
    return false;
  }
  if (columnPlot2.value) {
    columnPlot2.value.changeData(getOrderData.value);
  } else {
    columnPlot2.value = new Column("orderFormRef", {
      data: getOrderData.value,
      xField: "type",
      yField: "sales",
      meta: {
        type: {
          alias: "天"
        },
        sales: {
          alias: "订单数"
        }
      }
    });
    columnPlot2.value.render();
  }
};
//本年成交额
let yearTransactionData = ref<any>([]); //数据
const getYearTransaction = async () => {
  loadingYearTransaction.value = true;
  yearTransactionData.value = [];
  try {
    let data = await homeGetYearCount();
    for (let k in data.data) {
      if (k == "january") {
        yearTransactionData.value[0] = data.data[k];
      } else if (k == "february") {
        yearTransactionData.value[1] = data.data[k];
      } else if (k == "march") {
        yearTransactionData.value[2] = data.data[k];
      } else if (k == "april") {
        yearTransactionData.value[3] = data.data[k];
      } else if (k == "may") {
        yearTransactionData.value[4] = data.data[k];
      } else if (k == "june") {
        yearTransactionData.value[5] = data.data[k];
      } else if (k == "july") {
        yearTransactionData.value[6] = data.data[k];
      } else if (k == "august") {
        yearTransactionData.value[7] = data.data[k];
      } else if (k == "september") {
        yearTransactionData.value[8] = data.data[k];
      } else if (k == "october") {
        yearTransactionData.value[9] = data.data[k];
      } else if (k == "november") {
        yearTransactionData.value[10] = data.data[k];
      } else if (k == "december") {
        yearTransactionData.value[11] = data.data[k];
      }
    }
  } catch {
    for (let index = 1; index <= 12; index++) {
      yearTransactionData.value.push(0);
    }
  }
  yearTransaction();
  loadingYearTransaction.value = false;
};
const yearTransaction = () => {
  if (!yearTransactionRef.value) {
    return false;
  }
  var myChart = echarts.init(yearTransactionRef.value);
  var option;

  option = {
    title: {
      text: "本年成交额"
    },
    tooltip: {
      trigger: "axis"
    },
    // legend: {
    //   data: ["A", "B", "C", "D"]
    // },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true
    },
    toolbox: {
      feature: {
        saveAsImage: {}
      }
    },
    xAxis: {
      type: "category",
      boundaryGap: false,
      data: [
        `${dayjs().format("YYYY")}-01`,
        `${dayjs().format("YYYY")}-02`,
        `${dayjs().format("YYYY")}-03`,
        `${dayjs().format("YYYY")}-04`,
        `${dayjs().format("YYYY")}-05`,
        `${dayjs().format("YYYY")}-06`,
        `${dayjs().format("YYYY")}-07`,
        `${dayjs().format("YYYY")}-08`,
        `${dayjs().format("YYYY")}-09`,
        `${dayjs().format("YYYY")}-10`,
        `${dayjs().format("YYYY")}-11`,
        `${dayjs().format("YYYY")}-12`
      ]
    },
    yAxis: {
      type: "value"
    },
    series: [
      {
        name: "本年成交额",
        type: "line",
        stack: "Total",
        smooth: true,
        data: yearTransactionData.value
      }
      // {
      //   name: "B",
      //   type: "line",
      //   stack: "Total",
      //   smooth: true,
      //   data: []
      // },
      // {
      //   name: "C",
      //   type: "line",
      //   stack: "Total",
      //   smooth: true,
      //   data: []
      // },
      // {
      //   name: "D",
      //   type: "line",
      //   stack: "Total",
      //   smooth: true,
      //   data: []
      // }
    ]
  };
  // option.series.forEach((item) => {
  //   for (let index = 0; index < 12; index++) {
  //     item.data.push(Math.floor(Math.random() * 10000 + 1));
  //   }
  // });
  option && myChart.setOption(option);
};
//本月成交额TOP
const transactionTopData = ref([]); //数据
const getTransactionTop = async () => {
  loadingTransactionTop.value = true;
  try {
    let data = await homeGetMonethTopTenDto();
    transactionTopData.value = data.data;
  } catch {
    transactionTopData.value = [];
  }
  transactionTop();
  loadingTransactionTop.value = false;
};
const transactionTop = () => {
  if (!document.querySelector("#transactionTopRef")) {
    return false;
  }
  const columnPlot = new Column("transactionTopRef", {
    data: transactionTopData.value,
    xField: "name",
    yField: "moeny",
    meta: {
      type: {
        alias: "名称"
      },
      moeny: {
        alias: "成交额"
      }
    }
  });

  columnPlot.render();
};
//选择时间重新渲染
const getNewData = (data, name) => {
  if (name == "orderForm") {
    getOrderForm();
  } else if (name == "transaction") {
    getTransaction();
  }
};
</script>
<style lang="less" scoped>
#transactionTopRef {
  width: 60%;
  height: 400px;
}

#yearTransactionRef {
  width: 100%;
  height: 360px;
}

.tongji {
  width: 100%;
  display: flex;
  justify-content: space-between;
  height: 320px;
  margin-bottom: 50px;

  div {
    flex: 1;
    padding: 0 20px;
    box-sizing: border-box;

    .tongjiDev {
      width: 100%;
      height: 310px;
    }

    .commodityRef {
      padding: 0 !important;
    }
  }

  div:first-child {
    flex: 0.6;
  }
}

.nav {
  display: flex;
  justify-content: space-between;

  div {
    width: 184px;
    height: 108px;
    text-align: center;
    padding-top: 20px;
    cursor: pointer;

    img {
      margin-bottom: 10px;
      width: 30px;
    }
  }
}

.page-card-container-box {
  width: 100%;
  border-radius: 5px;
  background-color: rgba(255, 255, 255, 1);
  box-shadow: 0px 0px 10px 0px #dedede;
  min-height: calc(100vh - 330px);
  padding: 14px;
  position: relative;
}

.page-card-container-item {
  flex: 1;
  height: 200px;
  border-radius: 5px;
  background-color: rgba(255, 255, 255, 1);
  box-shadow: 0px 0px 10px 0px #dedede;
  padding: 14px 8px 14px 8px;
  margin-right: 20px;
}

.page-card-container-item:last-child {
  margin-right: 0px;
}

.top {
  display: flex;
  justify-content: space-around;
  margin-bottom: 14px;
}

.border {
  border-bottom: 1px solid rgb(211, 209, 209);
}
</style>
